/*
 * Principal.java
 *
 * Created on 10 de Agosto de 2009, 13:17
 */

package gui;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import javax.swing.JOptionPane;

import dados.BancoQuestoes;
import logica.GerenciaSerializacao;

/**
 *
 * @author  Yuri Maia
 * @author  Renato Leal
 */
public class Principal extends javax.swing.JFrame {
    
	private static final long serialVersionUID = 1L;
	/** Creates new form Principal */
    public Principal() {
        initComponents();
        this.setResizable(false);
        Janelas.alinharContainer(this);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        entradaMatricula = new javax.swing.JTextField();
        btnOk = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("GeradorProvas 1.1.1");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        entradaMatricula.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                entradaMatriculaActionPerformed(evt);
            }
        });

        btnOk.setText("OK");
        btnOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOkActionPerformed(evt);
            }
        });

        jLabel1.setText("Matrícula (Sete ou nove digitos)");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(entradaMatricula, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnOk))
                    .addComponent(jLabel1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(entradaMatricula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnOk))
                .addContainerGap(40, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed
        try{
            boolean semArquivo = false;

            /**Modificar para que o aluno nao abra caso nao exista um arquivo de estado */
            
            File pasta = new File(System.getProperty("user.dir"));
            File[] listaArquivos = pasta.listFiles(
                    new FileFilter() {
                        public boolean accept(File pathname) {
                            if(pathname.getAbsolutePath().endsWith(".ser"))
                                return true;
                            else
                                return false;
                        }
                    }
            );
            semArquivo = true;
            
            for(File arquivo: listaArquivos){
                try {
                    GerenciaSerializacao ser = new GerenciaSerializacao();
                    ser.desserializarBancoQuestoes(arquivo);
                    semArquivo = false;
                    break;
                }catch(ClassCastException e){
                
                }
            }
            
            if(entradaMatricula.getText().equals("Homero09")){
                JanelaProfessor jan = new JanelaProfessor(this, true);
                jan.setVisible(true);
            } else{
                Integer.parseInt(entradaMatricula.getText());
        		
        		if(!(entradaMatricula.getText().length() == 7 || entradaMatricula.getText().length() == 9)){
        			JOptionPane.showMessageDialog(null, "Voce deve inserir uma matricula de tamanho correto");
        			return ;
        		}
                
                if(!semArquivo) {
                	System.out.println(BancoQuestoes.getEscolha());
                    JanelaAluno jan = new JanelaAluno(this, true, entradaMatricula.getText());
                    jan.setVisible(true);
                } else {
                    throw new IOException();
                }
            }
        }catch(NumberFormatException e){
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "Informe uma matrícula válida\n(Apenas os números da sua matrícula)", "Erro!", JOptionPane.ERROR_MESSAGE);
        }catch(IOException e){
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "Não há banco de questões",
                    "Erro!", JOptionPane.ERROR_MESSAGE);
        }catch(IndexOutOfBoundsException e){
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "Banco de questões vazio",
                    "Erro!", JOptionPane.ERROR_MESSAGE);
        }
        this.setVisible(true);
    }//GEN-LAST:event_btnOkActionPerformed

    private void entradaMatriculaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_entradaMatriculaActionPerformed
        btnOk.doClick();
    }//GEN-LAST:event_entradaMatriculaActionPerformed
    
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Principal().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnOk;
    private javax.swing.JTextField entradaMatricula;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration//GEN-END:variables
    
}
